<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="培训类别" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择培训类别" clearable size="small">
          <el-option
            v-for="dict in levelOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['train:train:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['train:train:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['train:train:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['train:train:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="trainList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="培训类别" align="center" prop="level" :formatter="levelFormat" />
      <el-table-column label="培训时间" align="center" prop="trainDate" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.trainDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createDate" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="修改时间" align="center" prop="updateDate" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.updateDate, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="标题" align="center" prop="title"  />
      <el-table-column label="培训内容" align="center" prop="content"  />
      <el-table-column label="培训人员" align="center" prop="users" />
      <el-table-column label="培训课时" align="center" prop="hour"  />
      <el-table-column label="备注" align="center" prop="remark"  />
<!--      <el-table-column label="受训人签字" align="center" prop="sign"  />-->
      <el-table-column label="培训效果" align="center" prop="effect"  />
      <el-table-column label="培训总结" align="center" prop="summary"  />
      <el-table-column label="受训人" align="center" prop="userId"  :formatter = "userFormat"/>

      <el-table-column label="考试时间" align="center" prop="examDate" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.examDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考试成绩" align="center" prop="examScore"  />
      <el-table-column label="录入人" align="center" prop="enterUserId" :formatter = "enterUserFormat" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['train:train:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['train:train:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改train对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="培训类别" prop="level">
          <el-select v-model="form.level" placeholder="请选择培训类别">
            <el-option
              v-for="dict in levelOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="培训时间" prop="trainDate">
          <el-date-picker clearable size="small"
            v-model="form.trainDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择培训时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="培训内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="培训人员" prop="users">
          <el-input v-model="form.users" type="textarea" placeholder="请输入培训人员" />
        </el-form-item>
        <el-form-item label="培训课时" prop="hour">
       <el-input-number v-model="form.hour" placeholder="请输入培训课时"  :precision='4'>
        </el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="培训效果" prop="effect" v-if="form.level ==4">
          <el-input v-model="form.effect" type="textarea" placeholder="请输入培训效果" />
        </el-form-item>
        <el-form-item label="培训总结" prop="summary">
          <el-input v-model="form.summary" type="textarea" placeholder="请输入培训总结" />
        </el-form-item>

        <el-form-item label="考试时间" prop="examDate" v-if="form.level!=4">
          <el-date-picker clearable size="small"
                          v-model="form.examDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择考试时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考试成绩" prop="examScore" v-if="form.level!=4">
          <el-input-number v-model="form.examScore" placeholder="请输入考试成绩"  :precision='4'>
          </el-input-number>
        </el-form-item>

        <el-form-item label="受训人"  prop="userId" >
<!--          <el-select  v-model="form.userId" filterable disabled placeholder="选择受训人" @change="handleChange">-->
<!--            <el-option-->
<!--              v-for="one in filteredUsers"-->
<!--              :key="one.userId"-->
<!--              :label="one.nickName + ' (' + one.userName + ')'"-->
<!--              :value="one.userId">-->
<!--            </el-option>-->
<!--          </el-select>-->
          {{staticUser.nickName}}
        </el-form-item>
        <el-form-item label="受训人签字" prop="sign"  >
          <el-card :body-style="{ padding: '0px' }">
            <el-image
              :style="imgStyle"
              :src= "creatUrl(form.sign)"
              :fit="fits"></el-image>
          </el-card>
        </el-form-item>
        <el-form-item label="录入人" prop="enterUserId"  disabled="true">


          <el-select  v-model="form.enterUserId" filterable placeholder="选择录入人" disabled @change="handleChange">
            <el-option
              v-for="user in filteredUsers"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId">
            </el-option>
          </el-select>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTrain, getTrain, delTrain, addTrain, updateTrain, exportTrain } from "@/api/train/train";
import { listUserNoPage } from '@/api/system/user'
import { baseApiUrl } from '@/config/sysinfo'

export default {
  name: "Train",
  data() {
    return {
      staticUserId:null,
      staticUser:{},
      fits: 'fill',
      imgStyle: 'width: 100%; height: auto',
      filteredUsers:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // train表格数据
      trainList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // id字典
      idOptions: [],
      // 培训类别字典
      levelOptions: [],
      // 培训时间字典
      trainDateOptions: [],
      // 创建时间字典
      createDateOptions: [],
      // 修改时间字典
      updateDateOptions: [],
      // 培训内容字典
      contentOptions: [],
      // 培训人员字典
      usersOptions: [],
      // 培训课时字典
      hourOptions: [],
      // 备注字典
      remarkOptions: [],
      // 备注字典
      extar1Options: [],
      // 备注字典
      extar2Options: [],
      // 备注字典
      extar3Options: [],
      // 备注字典
      extar4Options: [],
      // 备注字典
      extar5Options: [],
      // 备注字典
      extar6Options: [],
      // 受训人签字字典
      signOptions: [],
      // 培训效果字典
      effectOptions: [],
      // 培训总结字典
      summaryOptions: [],
      // 受训人id字典
      userIdOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        level: null,
        userId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        level: [
          { required: true, message: "培训类别不能为空", trigger: "blur" }
        ],
        trainDate: [
          { required: true, message: "培训时间不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        hour: [
          { required: true, message: "培训课时不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    const userId = this.$route.params && this.$route.params.userId;
    this.queryParams.userId=userId
    this.staticUserId=userId
    this.form.userId = userId
    this.fetchUsers();


    this.getList();
    this.getDicts("${column.dictType}").then(response => {
      this.idOptions = response.data;
    });
    this.getDicts("train_type").then(response => {
      this.levelOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.trainDateOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.createDateOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.updateDateOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.contentOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.usersOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.hourOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.remarkOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extar1Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extar2Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extar3Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extar4Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extar5Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extar6Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.signOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.effectOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.summaryOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.userIdOptions = response.data;
    });
  },
  // watch: {
  //   'form.userId': function(newVal, oldVal) {
  //     if (newVal) {
  //       // 找到对应的用户
  //       let user = this.filteredUsers.find(o => o.userId === newVal);
  //       if (user) {
  //         // 如果用户存在，则检查签名
  //         if (!user.sign) {
  //           this.$modal.msgError("该用户未维护签名信息,请先维护");
  //           this.form.userId = oldVal; // 恢复到之前的值
  //         } else {
  //           this.form.sign = user.sign; // 设置签名
  //         }
  //       } else {
  //         // 如果用户不存在，恢复到旧值
  //         this.form.userId = oldVal;
  //       }
  //     }
  //   }
  // },

  methods: {
    enterUserFormat(row, column) {

      const user = this.filteredUsers.find(user => user.userId === row.enterUserId);

      return user ? user.userName: '';
    },
    userFormat(row, column) {
      const user = this.filteredUsers.find(user => user.userId === row.userId);
      return user ? user.userName: '';
    },
    creatUrl (urlpath) {
      let url = process.env.VUE_APP_BASE_API + urlpath

      return url
    },
    fetchUsers() {
      this.loading=true;
      listUserNoPage().then(response => {
          this.filteredUsers = response.rows;
          this.loading = false;
        }
      );
    },
    handleChange(value) {
      console.log("Selected user ID:", value)
    },
    /** 查询train列表 */
    getList() {
      this.loading = true;
      listTrain(this.queryParams).then(response => {
        this.trainList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // id字典翻译
    idFormat(row, column) {
      return this.selectDictLabel(this.idOptions, row.id);
    },
    // 培训类别字典翻译
    levelFormat(row, column) {
      return this.selectDictLabel(this.levelOptions, row.level);
    },
    // 培训时间字典翻译
    trainDateFormat(row, column) {
      return this.selectDictLabel(this.trainDateOptions, row.trainDate);
    },
    // 创建时间字典翻译
    createDateFormat(row, column) {
      return this.selectDictLabel(this.createDateOptions, row.createDate);
    },
    // 修改时间字典翻译
    updateDateFormat(row, column) {
      return this.selectDictLabel(this.updateDateOptions, row.updateDate);
    },
    // 培训内容字典翻译
    contentFormat(row, column) {
      return this.selectDictLabel(this.contentOptions, row.content);
    },
    // 培训人员字典翻译
    usersFormat(row, column) {
      return this.selectDictLabel(this.usersOptions, row.users);
    },
    // 培训课时字典翻译
    hourFormat(row, column) {
      return this.selectDictLabel(this.hourOptions, row.hour);
    },
    // 备注字典翻译
    remarkFormat(row, column) {
      return this.selectDictLabel(this.remarkOptions, row.remark);
    },
    // 备注字典翻译
    extar1Format(row, column) {
      return this.selectDictLabel(this.extar1Options, row.extar1);
    },
    // 备注字典翻译
    extar2Format(row, column) {
      return this.selectDictLabel(this.extar2Options, row.extar2);
    },
    // 备注字典翻译
    extar3Format(row, column) {
      return this.selectDictLabel(this.extar3Options, row.extar3);
    },
    // 备注字典翻译
    extar4Format(row, column) {
      return this.selectDictLabel(this.extar4Options, row.extar4);
    },
    // 备注字典翻译
    extar5Format(row, column) {
      return this.selectDictLabel(this.extar5Options, row.extar5);
    },
    // 备注字典翻译
    extar6Format(row, column) {
      return this.selectDictLabel(this.extar6Options, row.extar6);
    },
    // 受训人签字字典翻译
    signFormat(row, column) {
      return this.selectDictLabel(this.signOptions, row.sign);
    },
    // 培训效果字典翻译
    effectFormat(row, column) {
      return this.selectDictLabel(this.effectOptions, row.effect);
    },
    // 培训总结字典翻译
    summaryFormat(row, column) {
      return this.selectDictLabel(this.summaryOptions, row.summary);
    },
    // 受训人id字典翻译
    userIdFormat(row, column) {
      return this.selectDictLabel(this.userIdOptions, row.userId);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        level: null,
        trainDate: null,
        createDate: null,
        updateDate: null,
        content: null,
        users: null,
        hour: null,
        remark: null,
        extar1: null,
        extar2: null,
        extar3: null,
        extar4: null,
        extar5: null,
        extar6: null,
        sign: null,
        effect: null,
        summary: null,
        enterUserId:null,
        userId: null,
        examScore:null,
        examDate:null,
        title:null
      };
      this.resetForm("form");

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.userId=this.staticUserId
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.fetchUsers();
      let currentUser = this.$store.state.user;
      this.form.enterUserId = currentUser.userId;
      this.form.userId = this.staticUserId;
      let shouxunren = this.filteredUsers.find(o => o.userId == this.form.userId);
this.staticUser=shouxunren
      this.form.sign = shouxunren.sign
      this.open = true;
      this.title = "添加培训记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTrain(id).then(response => {
        this.form = response.data;
        let shouxunren = this.filteredUsers.find(o => o.userId == this.form.userId);
        this.staticUser=shouxunren
        this.open = true;
        this.title = "修改培训记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTrain(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTrain(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除培训编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTrain(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有培训数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
        this.download('/train/train/export', {
          ...this.queryParams
        }, `培训记录.xlsx`)
        this.exportLoading = false;
          // return exportTrain(queryParams);
        }).then(response => {
          // this.download(response.msg);
          // this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
